import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react-swc'
import AutoImport from 'unplugin-auto-import/vite'
import path from 'path'

export function getCurrentTime() {
  const date = new Date()
  const year: number | string = date.getFullYear()
  const month: number | string = date.getMonth() + 1
  const day: number | string = date.getDate()
  return year + '-' + month + '-' + day
}
// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  const versionInfo = getCurrentTime()
  console.log(process.env.npm_package_version)
  return {
    plugins: [
      react(),
      AutoImport({
        eslintrc: {
          enabled: true,
          filepath: './.eslintrc-auto-import.json', //此文件为重新启动项目生成的文件
        },
        dts: './auto-imports.d.ts', //此文件配置保存后系统自动生成
        imports: ['react', 'react-router-dom'], //此处可填写需要自动引入的库
      }),
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
      extensions: ['.js', '.jsx', '.ts', '.tsx'],
    },
    css: {
      // CSS 预处理器
      preprocessorOptions: {
        // 定义全局scss 变量
        scss: {
          javascriptEnabled: true,
          additionalData: `
            @use "@/assets/scss/mixin.scss" as *;
          `,
        },
      },
      modules: {
        localsConvention: 'camelCaseOnly',
      },
    },
    server: {
      host: '0.0.0.0',
      port: Number(env.VITE_APP_PORT),
      // 服务配置
      open: true, //配置自动启动浏览器  open: 'Google Chrome'-默认启动谷歌
      proxy: {
        [env.VITE_APP_BASE_API]: {
          changeOrigin: true,
          secure: false, // 禁用 SSL 证书验证
          // 接口地址
          target: env.VITE_APP_API_URL,
          // rewrite: (path) => path.replace(new RegExp('^' + env.VITE_APP_BASE_API), ''),
        },
      },
    },
    build: {
      outDir: 'dist',
      minify: 'esbuild',
      // esbuild 打包更快，但是不能去除 console.log，terser打包慢，但能去除 console.log
      // minify: "terser",
      // terserOptions: {
      // 	compress: {
      // 		drop_console: viteEnv.VITE_DROP_CONSOLE,
      // 		drop_debugger: true
      // 	}
      // },
      // 禁用 gzip 压缩大小报告，可略微减少打包时间
      reportCompressedSize: false,
      // 规定触发警告的 chunk 大小
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        //配置rollup
        output: {
          // 配置rollup输出选项
          // Static resource classification and packaging//静态资源分类打包
          chunkFileNames: `assets/js/[name]-${versionInfo}-[hash].js`, //代码块文件名
          entryFileNames: `assets/js/[name]-${versionInfo}-[hash].js`, //入口文件名
          assetFileNames: `assets/[ext]/[name]-${versionInfo}-[hash].[ext]`, // 资源文件名
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id
                .toString()
                .split('node_modules/')[2]
                .split('/')[0]
                .toString()
            }
          },
        },
      },
    },
  }
})
